package com.changkang.webim.mqtt;


import java.io.UnsupportedEncodingException;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;

import com.changkang.webim.common.QosType;
import com.jfinal.kit.LogKit;
/**
 * 自定义mqtt工具包
 * @author 常康
 *
 */
public class MqttKit {
	/**实例化以后的单例mqtt client*/
   private static MqttClient client;
   
   /**
    * 获取mqtt client实例
    * @param _client
    */
   public static void init(MqttClient _client){
		client = _client;
	}
   
   /**
    * 订阅主题，默认消息质量为2
    * @param topic  主题
    */
   public static boolean subscribe(String topic) {
	   try {
	  	 client.subscribe(topic, QosType.QOS_EXACTLY_ONCE.type());
	} catch (MqttException e) {
		LogKit.error("订阅"+topic+"主题失败！",e);
		return false;
	}
	   return true;
   }
   
   /**
    * 取消订阅主题
    * @param topic  主题
    */
   public static boolean unSubscribe(String topic) {
	   try {
		client.unsubscribe(topic);
	} catch (MqttException e) {
		LogKit.error("取消订阅"+topic+"主题失败！",e);
		return false;
	}
	   return true;
   }
   
   /**
    * 发送消息,发送消息时需要先判断对方是否在线
    * @param topic  消息主题
    * @param content  消息内容
    * @return
    */
   public static boolean sendMessage(String topic ,String content) {
	   MqttMessage message=new MqttMessage();
	   try {
		message.setPayload(content.getBytes("UTF-8"));
	} catch (UnsupportedEncodingException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	   message.setQos(QosType.QOS_EXACTLY_ONCE.type());
	   message.setRetained(false);
	   try {
		client.publish(topic, message);
	} catch (MqttPersistenceException e) {
		LogKit.error(topic+"发送消息失败",e);
		return false;
	} catch (MqttException e) {
		LogKit.error(topic+"发送消息失败",e);
		return false;
	}
	   return true;
   } 
}
